package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.OaConfig;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TbVehicleIllegal;
import com.ruoyi.system.domain.TbVisitorUser;
import com.ruoyi.system.domain.TbVisitorVehicle;
import com.ruoyi.system.domain.vo.VoVehicle;
import com.ruoyi.system.service.IOaService;
import com.weaver.esb.spi.EsbManager;
import com.weaver.esb.spi.EsbService;
import com.weaver.esb.spi.RequestConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * OA系统Service业务处理层
 *
 * @author lxy
 * @date 2025-04-23
 */
@Service
public class OaServiceImpl implements IOaService {

    private static final Logger log = LoggerFactory.getLogger(OaServiceImpl.class);

    @Autowired
    private OaConfig oaConfig;

    @Override
    public String createUserWorkflow(TbVisitorUser visitorUser) {
        RequestConfig requestConfig = new RequestConfig();
        requestConfig.setAppKey(oaConfig.getAppKey());
        requestConfig.setServerUrl(oaConfig.getServerUrl());
        requestConfig.setSign(oaConfig.getSign());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("requestName", "访客预约流程");
        jsonObject.put("workflowId", oaConfig.getUserWorkflowId());

        JSONArray mainData = new JSONArray();
        JSONObject xm = new JSONObject();
        xm.put("fieldName", "xm");
        xm.put("fieldValue", visitorUser.getUserName());
        mainData.add(xm);
        JSONObject dw = new JSONObject();
        dw.put("fieldName", "dw");
        dw.put("fieldValue", visitorUser.getCompanyFrom());
        mainData.add(dw);
        JSONObject lxfs = new JSONObject();
        lxfs.put("fieldName", "lxfs");
        lxfs.put("fieldValue", visitorUser.getPhone());
        mainData.add(lxfs);
        JSONObject sqrq = new JSONObject();
        sqrq.put("fieldName", "sqrq");
        sqrq.put("fieldValue", LocalDate.now());
        mainData.add(sqrq);
        JSONObject lfsy = new JSONObject();
        lfsy.put("fieldName", "lfsy");
        lfsy.put("fieldValue", DictUtils.getDictLabel("visitor_user", visitorUser.getCustomersType()) + "-" + DictUtils.getDictLabel(visitorUser.getCustomersType(), visitorUser.getVisitorType()) + (StringUtils.isEmpty(visitorUser.getVisitReason()) ? "" : ("-" + visitorUser.getVisitReason())));
        mainData.add(lfsy);

        List<SysDictData> customersTypeList = DictUtils.getDictCache("visitor_user");
        for (SysDictData customersItem : customersTypeList) {
            if (customersItem.getDictValue().equals(visitorUser.getCustomersType())) {
                JSONObject lfsyyjfl = new JSONObject();
                lfsyyjfl.put("fieldName", "lfsyyjfl");
                lfsyyjfl.put("fieldValue", customersItem.getDictCode());
                mainData.add(lfsyyjfl);
                break;
            }
        }

        List<SysDictData> visitorTypeList = DictUtils.getDictCache(visitorUser.getCustomersType());
        for (SysDictData visitorItem : visitorTypeList) {
            if (visitorItem.getDictValue().equals(visitorUser.getVisitorType())) {
                JSONObject lfsyejfl = new JSONObject();
                lfsyejfl.put("fieldName", "lfsyejfl");
                lfsyejfl.put("fieldValue", visitorItem.getDictCode());
                mainData.add(lfsyejfl);
                break;
            }
        }

        JSONObject dfdw = new JSONObject();
        dfdw.put("fieldName", "dfdw");
        dfdw.put("fieldValue", DictUtils.getDictLabel("visiting_unit", visitorUser.getCompanyTo()));
        mainData.add(dfdw);
        JSONObject sfygbh = new JSONObject();
        sfygbh.put("fieldName", "sfygbh");
        sfygbh.put("fieldValue", visitorUser.getInterviewedNo());
        mainData.add(sfygbh);
        JSONObject sfygxmhz = new JSONObject();
        sfygxmhz.put("fieldName", "sfygxmhz");
        sfygxmhz.put("fieldValue", visitorUser.getInterviewedName());
        mainData.add(sfygxmhz);
        JSONObject jrsj = new JSONObject();
        jrsj.put("fieldName", "jrsj");
        jrsj.put("fieldValue", visitorUser.getInTime());
        mainData.add(jrsj);
        JSONObject lksj = new JSONObject();
        lksj.put("fieldName", "lksj");
        lksj.put("fieldValue", visitorUser.getOutTime());
        mainData.add(lksj);
        JSONObject sfzjsz = new JSONObject();
        sfzjsz.put("fieldName", "sfzjsz");
        sfzjsz.put("fieldValue", formatUrl(visitorUser.getCardImg()));
        mainData.add(sfzjsz);
        JSONObject bx = new JSONObject();
        bx.put("fieldName", "bx");
        bx.put("fieldValue", formatUrl(visitorUser.getInsurance()));
        mainData.add(bx);
        JSONObject tzzyz = new JSONObject();
        tzzyz.put("fieldName", "tzzyz");
        tzzyz.put("fieldValue", formatUrl(visitorUser.getSpecialOperations()));
        mainData.add(tzzyz);

        jsonObject.put("mainData", JSONObject.toJSONString(mainData));
        jsonObject.put("remark", "同意");
        jsonObject.put("usercode", visitorUser.getInterviewedNo());
        jsonObject.put("username", visitorUser.getInterviewedName());

        String params = jsonObject.toString();
        EsbService service = EsbManager.getService("http", requestConfig);
        log.info("请求接口 {} , 请求参数  {}  ", "访客预约流程", params);
        String result = service.execute(oaConfig.getEventKey(), params);
        log.info("请求接口 {} , 返回结果  {}  ", "访客预约流程", result);
        return result;
    }

    @Override
    public String createVehicleWorkflow(VoVehicle visitorVehicle) {
        RequestConfig requestConfig = new RequestConfig();
        requestConfig.setAppKey(oaConfig.getAppKey());
        requestConfig.setServerUrl(oaConfig.getServerUrl());
        requestConfig.setSign(oaConfig.getSign());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("requestName", "访客车辆预约流程");
        jsonObject.put("workflowId", oaConfig.getCarWorkflowId());

        JSONArray mainData = new JSONArray();
        JSONObject xm = new JSONObject();
        xm.put("fieldName", "xm");
        xm.put("fieldValue", visitorVehicle.getUserName());
        mainData.add(xm);
        JSONObject dw = new JSONObject();
        dw.put("fieldName", "dw");
        dw.put("fieldValue", visitorVehicle.getCompanyFrom());
        mainData.add(dw);
        JSONObject lxfs = new JSONObject();
        lxfs.put("fieldName", "lxfs");
        lxfs.put("fieldValue", visitorVehicle.getPhone());
        mainData.add(lxfs);
        JSONObject sqrq = new JSONObject();
        sqrq.put("fieldName", "sqrq");
        sqrq.put("fieldValue", LocalDate.now());
        mainData.add(sqrq);
        JSONObject lfsy = new JSONObject();
        lfsy.put("fieldName", "lfsy");
        lfsy.put("fieldValue", DictUtils.getDictLabel("visitor_vehicle", visitorVehicle.getCustomersType()) + "-" + DictUtils.getDictLabel(visitorVehicle.getCustomersType(), visitorVehicle.getVisitorType()) + (StringUtils.isEmpty(visitorVehicle.getVisitReason()) ? "" : ("-" + visitorVehicle.getVisitReason())));
        mainData.add(lfsy);

        List<SysDictData> customersTypeList = DictUtils.getDictCache("visitor_vehicle");
        for (SysDictData customersItem : customersTypeList) {
                if (customersItem.getDictValue().equals(visitorVehicle.getCustomersType())) {
                    JSONObject lfsyyjfl = new JSONObject();
                    lfsyyjfl.put("fieldName", "lfsyyjfl");
                    lfsyyjfl.put("fieldValue", customersItem.getDictCode());
                    mainData.add(lfsyyjfl);
                    break;
                }
        }

        List<SysDictData> visitorTypeList = DictUtils.getDictCache(visitorVehicle.getCustomersType());
        for (SysDictData visitorItem : visitorTypeList) {
            if (visitorItem.getDictValue().equals(visitorVehicle.getVisitorType())) {
                JSONObject lfsyejfl = new JSONObject();
                lfsyejfl.put("fieldName", "lfsyejfl");
                lfsyejfl.put("fieldValue", visitorItem.getDictCode());
                mainData.add(lfsyejfl);
                break;
            }
        }

        JSONObject dfdw = new JSONObject();
        dfdw.put("fieldName", "dfdw");
        dfdw.put("fieldValue", DictUtils.getDictLabel("visiting_unit", visitorVehicle.getCompanyTo()));
        mainData.add(dfdw);
        JSONObject sfygbh = new JSONObject();
        sfygbh.put("fieldName", "sfygbh");
        sfygbh.put("fieldValue", visitorVehicle.getInterviewedNo());
        mainData.add(sfygbh);
        JSONObject sfygxmhz = new JSONObject();
        sfygxmhz.put("fieldName", "sfygxmwz");
        sfygxmhz.put("fieldValue", visitorVehicle.getInterviewedName());
        mainData.add(sfygxmhz);
        JSONObject cph = new JSONObject();
        cph.put("fieldName", "cph");
        cph.put("fieldValue", visitorVehicle.getCard());
        mainData.add(cph);
        JSONObject cllx = new JSONObject();
        cllx.put("fieldName", "cllx");
        String vehicleType="0";
        if (StringUtils.isNotBlank(visitorVehicle.getVehicleType()))
        {
            vehicleType = visitorVehicle.getVehicleType();
        }
        cllx.put("fieldValue", DictUtils.getDictLabel("vehicle_type", vehicleType));
        mainData.add(cllx);
        JSONObject xsz = new JSONObject();
        xsz.put("fieldName", "xsz");
        xsz.put("fieldValue", formatUrl(visitorVehicle.getDrivingLicense()));
        mainData.add(xsz);
        JSONObject jsz = new JSONObject();
        jsz.put("fieldName", "jsz");
        jsz.put("fieldValue", formatUrl(visitorVehicle.getDriverLicense()));
        mainData.add(jsz);
        JSONObject jrsj = new JSONObject();
        jrsj.put("fieldName", "jrsj");
        jrsj.put("fieldValue", visitorVehicle.getInTime());
        mainData.add(jrsj);
        JSONObject lksj = new JSONObject();
        lksj.put("fieldName", "lksj");
        lksj.put("fieldValue", visitorVehicle.getOutTime());
        mainData.add(lksj);
        JSONObject sfgb = new JSONObject();
        sfgb.put("fieldName", "sfgb");
        sfgb.put("fieldValue", "0".equals(visitorVehicle.getIfWeighing()) ? "否": "是");
        mainData.add(sfgb);
        JSONObject gbwz = new JSONObject();
        gbwz.put("fieldName", "gbwz");
        gbwz.put("fieldValue", visitorVehicle.getWeighingItems());
        mainData.add(gbwz);
        JSONObject sfxdwp = new JSONObject();
        sfxdwp.put("fieldName", "sfxdwp");
        sfxdwp.put("fieldValue", "0".equals(visitorVehicle.getIfGoods()) ? "否": "是");
        mainData.add(sfxdwp);

        JSONArray detailData = new JSONArray();
        // 车辆物品
        if ("1".equals(visitorVehicle.getIfGoods())) {
            JSONObject clwp = new JSONObject();
            clwp.put("tableDBName", oaConfig.getFlowTableDBName());
            JSONArray clwpRecords = new JSONArray();
            visitorVehicle.getGoodsList().forEach(goods -> {
                JSONObject clwpRecord = new JSONObject();
                clwpRecord.put("recordOrder", 0);
                JSONArray clwpFields = new JSONArray();
                JSONObject wpmc = new JSONObject();
                wpmc.put("fieldName", "wpmc");
                wpmc.put("fieldValue", goods.getGoodsName());
                clwpFields.add(wpmc);
                JSONObject sl = new JSONObject();
                sl.put("fieldName", "sl");
                sl.put("fieldValue", goods.getGoodsNum());
                clwpFields.add(sl);
                JSONObject ggpp = new JSONObject();
                ggpp.put("fieldName", "ggpp");
                ggpp.put("fieldValue", goods.getBrand());
                clwpFields.add(ggpp);
                JSONObject zp = new JSONObject();
                zp.put("fieldName", "zp");
                zp.put("fieldValue", formatUrl(goods.getPhoto()));
                clwpFields.add(zp);
                clwpRecord.put("workflowRequestTableFields", clwpFields);
                clwpRecords.add(clwpRecord);
            });
            clwp.put("WorkflowRequestTableRecords", clwpRecords);
            detailData.add(clwp);
        }
        // 随车人员
        if ("1".equals(visitorVehicle.getIfFollower())) {
            JSONObject scry = new JSONObject();
            scry.put("tableDBName", oaConfig.getUserTableDBName());
            JSONArray scryRecords = new JSONArray();
            visitorVehicle.getFollowerList().forEach(follower -> {
                JSONObject scryRecord = new JSONObject();
                scryRecord.put("recordOrder", 0);
                JSONArray scryFields = new JSONArray();
                JSONObject scryXm = new JSONObject();
                scryXm.put("fieldName", "xm");
                scryXm.put("fieldValue", follower.getUserName());
                scryFields.add(scryXm);
                JSONObject scryDh = new JSONObject();
                scryDh.put("fieldName", "dh");
                scryDh.put("fieldValue", follower.getPhonenumber());
                scryFields.add(scryDh);
                JSONObject scryBx = new JSONObject();
                scryBx.put("fieldName", "bx");
                scryBx.put("fieldValue", formatUrl(follower.getInsurance()));
                scryFields.add(scryBx);
                JSONObject scrySfz = new JSONObject();
                scrySfz.put("fieldName", "sfz");
                scrySfz.put("fieldValue", formatUrl(follower.getCard()));
                scryFields.add(scrySfz);
                JSONObject scryTzzyz = new JSONObject();
                scryTzzyz.put("fieldName", "tzzyz");
                scryTzzyz.put("fieldValue", formatUrl(follower.getSpecialOperations()));
                scryFields.add(scryTzzyz);
                scryRecord.put("workflowRequestTableFields", scryFields);
                scryRecords.add(scryRecord);
            });
            scry.put("WorkflowRequestTableRecords", scryRecords);
            detailData.add(scry);
        }

        jsonObject.put("mainData", JSONObject.toJSONString(mainData));
        jsonObject.put("detailData", JSONObject.toJSONString(detailData));
        jsonObject.put("remark", "同意");
        jsonObject.put("usercode", visitorVehicle.getInterviewedNo());
        jsonObject.put("username", visitorVehicle.getInterviewedName());

        String params = jsonObject.toString();
        EsbService service = EsbManager.getService("http", requestConfig);
        log.info("请求接口 {} , 请求参数  {}  ", "访客车辆预约流程", params);
        String result = service.execute(oaConfig.getEventKey(), params);
        log.info("请求接口 {} , 返回结果  {}  ", "访客车辆预约流程", result);
        return result;
    }

    @Override
    public String createVehicleIllegalWorkflow(TbVehicleIllegal vehicleIllegal) {
        RequestConfig requestConfig = new RequestConfig();
        requestConfig.setAppKey(oaConfig.getAppKey());
        requestConfig.setServerUrl(oaConfig.getServerUrl());
        requestConfig.setSign(oaConfig.getSign());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("requestName", "违章审批流程");
        jsonObject.put("workflowId", oaConfig.getIllegalWorkflowId());

        JSONArray mainData = new JSONArray();
        JSONObject clpz = new JSONObject();
        clpz.put("fieldName", "clpz");
        clpz.put("fieldValue", vehicleIllegal.getLicenseNo());
        mainData.add(clpz);
        JSONObject czxm = new JSONObject();
        czxm.put("fieldName", "czxm");
        czxm.put("fieldValue", vehicleIllegal.getCarOwner());
        mainData.add(czxm);
        JSONObject clcspz = new JSONObject();
        clcspz.put("fieldName", "clcspz");
        clcspz.put("fieldValue", vehicleIllegal.getOverspeedImgUrl());
        mainData.add(clcspz);
        JSONObject clxssd = new JSONObject();
        clxssd.put("fieldName", "clxssd");
        clxssd.put("fieldValue", vehicleIllegal.getSpeed());
        mainData.add(clxssd);
        JSONObject clcsrq = new JSONObject();
        clcsrq.put("fieldName", "clcsrq");
        clcsrq.put("fieldValue", vehicleIllegal.getOverspeedDate());
        mainData.add(clcsrq);
        JSONObject sfygbh = new JSONObject();
        sfygbh.put("fieldName", "sfygbh");
        sfygbh.put("fieldValue", vehicleIllegal.getInterviewedNo());
        mainData.add(sfygbh);
        JSONObject sfygxmhz = new JSONObject();
        sfygxmhz.put("fieldName", "sfygxmhz");
        sfygxmhz.put("fieldValue", vehicleIllegal.getInterviewedName());
        mainData.add(sfygxmhz);

        jsonObject.put("mainData", JSONObject.toJSONString(mainData));
        jsonObject.put("remark", "同意");
        jsonObject.put("usercode", vehicleIllegal.getInterviewedNo());
        jsonObject.put("username", vehicleIllegal.getInterviewedName());

        String params = jsonObject.toString();
        EsbService service = EsbManager.getService("http", requestConfig);
        log.info("请求接口 {} , 请求参数  {}  ", "违章审批流程", params);
        String result = service.execute(oaConfig.getEventKey(), params);
        log.info("请求接口 {} , 返回结果  {}  ", "违章审批流程", result);
        return result;
    }

    @Override
    public String createWeightTimeoutWorkflow(TbVisitorVehicle visitorVehicle) {
        RequestConfig requestConfig = new RequestConfig();
        requestConfig.setAppKey(oaConfig.getAppKey());
        requestConfig.setServerUrl(oaConfig.getServerUrl());
        requestConfig.setSign(oaConfig.getSign());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("requestName", "过磅超时审批流程");
        jsonObject.put("workflowId", oaConfig.getTimeoutWorkflowId());

        JSONArray mainData = new JSONArray();
        JSONObject xm = new JSONObject();
        xm.put("fieldName", "xm");
        xm.put("fieldValue", visitorVehicle.getUserName());
        mainData.add(xm);
        JSONObject dw = new JSONObject();
        dw.put("fieldName", "dw");
        dw.put("fieldValue", visitorVehicle.getCompanyFrom());
        mainData.add(dw);
        JSONObject lxfs = new JSONObject();
        lxfs.put("fieldName", "lxfs");
        lxfs.put("fieldValue", visitorVehicle.getPhone());
        mainData.add(lxfs);
        JSONObject sqrq = new JSONObject();
        sqrq.put("fieldName", "sqrq");
        sqrq.put("fieldValue", LocalDate.now());
        mainData.add(sqrq);
        JSONObject lfsy = new JSONObject();
        lfsy.put("fieldName", "lfsy");
        lfsy.put("fieldValue", DictUtils.getDictLabel("visitor_vehicle", visitorVehicle.getCustomersType()) + "-" + DictUtils.getDictLabel(visitorVehicle.getCustomersType(), visitorVehicle.getVisitorType()) + (StringUtils.isEmpty(visitorVehicle.getVisitReason()) ? "" : ("-" + visitorVehicle.getVisitReason())));
        mainData.add(lfsy);
//
//        List<SysDictData> customersTypeList = DictUtils.getDictCache("visitor_vehicle");
//        for (SysDictData customersItem : customersTypeList) {
//            if (customersItem.getDictValue().equals(visitorVehicle.getCustomersType())) {
//                JSONObject lfsyyjfl = new JSONObject();
//                lfsyyjfl.put("fieldName", "lfsyyjfl");
//                lfsyyjfl.put("fieldValue", customersItem.getDictCode());
//                mainData.add(lfsyyjfl);
//                break;
//            }
//        }
//
//        List<SysDictData> visitorTypeList = DictUtils.getDictCache(visitorVehicle.getCustomersType());
//        for (SysDictData visitorItem : visitorTypeList) {
//            if (visitorItem.getDictValue().equals(visitorVehicle.getVisitorType())) {
//                JSONObject lfsyejfl = new JSONObject();
//                lfsyejfl.put("fieldName", "lfsyejfl");
//                lfsyejfl.put("fieldValue", visitorItem.getDictCode());
//                mainData.add(lfsyejfl);
//                break;
//            }
//        }

        JSONObject sfygbh = new JSONObject();
        sfygbh.put("fieldName", "sfygbh");
        sfygbh.put("fieldValue", "DZ2014066");
        mainData.add(sfygbh);
        JSONObject sfygxmhz = new JSONObject();
        sfygxmhz.put("fieldName", "sfygxmhz");
        sfygxmhz.put("fieldValue", "qq");
        mainData.add(sfygxmhz);
        JSONObject cph = new JSONObject();
        cph.put("fieldName", "cph");
        cph.put("fieldValue", visitorVehicle.getCard());
        mainData.add(cph);
        JSONObject cllx = new JSONObject();
        cllx.put("fieldName", "cllx");
        String vehicleType="0";
        if (StringUtils.isNotBlank(visitorVehicle.getVehicleType()))
        {
            vehicleType = visitorVehicle.getVehicleType();
        }
        cllx.put("fieldValue", DictUtils.getDictLabel("vehicle_type", vehicleType));
        mainData.add(cllx);
        JSONObject jrsj = new JSONObject();
        jrsj.put("fieldName", "jrsj");
        jrsj.put("fieldValue", visitorVehicle.getInTime());
        mainData.add(jrsj);
        JSONObject lksj = new JSONObject();
        lksj.put("fieldName", "lksj");
        lksj.put("fieldValue", visitorVehicle.getOutTime());
        mainData.add(lksj);
        JSONObject sfgb = new JSONObject();
        sfgb.put("fieldName", "sfgb");
        sfgb.put("fieldValue", "0".equals(visitorVehicle.getIfWeighing()) ? "否": "是");
        mainData.add(sfgb);
        JSONObject gbwz = new JSONObject();
        gbwz.put("fieldName", "gbwz");
        gbwz.put("fieldValue", visitorVehicle.getWeighingItems());
        mainData.add(gbwz);
        JSONObject sfxdwp = new JSONObject();
        sfxdwp.put("fieldName", "sfxdwp");
        sfxdwp.put("fieldValue", "0".equals(visitorVehicle.getIfGoods()) ? "否": "是");
        mainData.add(sfxdwp);

        jsonObject.put("mainData", JSONObject.toJSONString(mainData));
        jsonObject.put("remark", "同意");
        jsonObject.put("usercode", "DZ2014066");
        jsonObject.put("username", "qq");

        String params = jsonObject.toString();
        EsbService service = EsbManager.getService("http", requestConfig);
        log.info("请求接口 {} , 请求参数  {}  ", "过磅超时审批流程", params);
        String result = service.execute(oaConfig.getEventKey(), params);
        log.info("请求接口 {} , 返回结果  {}  ", "过磅超时审批流程", result);
        return result;
    }



    private static String formatUrl(String urls) {
        String result = "";
        if (StringUtils.isNotEmpty(urls)) {
            String[] array = urls.split(",");
            List<String> list = new ArrayList<>();
            for (String url : array) {
                list.add(url.substring(0, url.lastIndexOf("/") + 1) + ";" + url.substring(url.lastIndexOf("/") + 1));
            }
            result = String.join(",", list);
        }
        return result;
    }
}
